package edu.ccut.saturn.component.loader.node;

import java.util.ArrayList;
import java.util.List;

import org.dom4j.Element;
import org.osgi.framework.Bundle;

import edu.ccut.saturn.component.INodeInfo;
import edu.ccut.saturn.component.IParameterInfo;
import edu.ccut.saturn.component.SaturnComponentException;
import edu.ccut.saturn.component.impl.node.BaseComponentNodeInfo;

/**
 * 解析用于logic中出现的基础组件节点"component"的xml配置信息
 * <p>
 * 
 * @author 谷钰
 * @version 1.0 2008.8.13
 * 
 * @see BaseComponentNodeInfo
 */
public class BaseComponentNodeInfoLoader extends NodeInfoLoader {

	public static final String KEY_NODETYPE_COMPONENT = "component";

	@SuppressWarnings("unchecked")
	public List<INodeInfo> loadNode(Element root, Bundle bundle)
			throws SaturnComponentException {

		List<Element> baseComponentElements = root
				.elements(KEY_NODETYPE_COMPONENT);

		List<INodeInfo> baseComponentNodeInfos = new ArrayList<INodeInfo>(
				baseComponentElements.size());

		for (Element baseComponentElement : baseComponentElements) {
			String key = baseComponentElement.elementTextTrim(KEY_NODE_KEY);
			//TODO:解析结点的try catch怎么写好
			try {
				String id = baseComponentElement.attributeValue(KEY_NODE_ID)
						.trim();
				String name = baseComponentElement
						.elementTextTrim(KEY_NODE_NAME);
				String description = baseComponentElement
						.elementTextTrim(KEY_NODE_DESCRIPTION);

				String nextId = baseComponentElement.attributeValue(
						KEY_NODE_NEXT).trim();

				String exceptionId = baseComponentElement.attributeValue(
						KEY_NODE_EXCEPTION).trim();
				
				String x = baseComponentElement.attributeValue(KEY_NODE_X)
						.trim();
				String y = baseComponentElement.attributeValue(KEY_NODE_Y)
						.trim();

				logger.debug("  load component node id = \"" + id + "\" key = \"" + key
						+ "\" name = \"" + name + "\" description = \""
						+ description + "\" nextId = \"" + nextId + "\"");
				
				List<IParameterInfo> parameters = getParameterInfos(bundle,
						baseComponentElement);
				
				BaseComponentNodeInfo baseComponentNodeInfo = new BaseComponentNodeInfo(
						id, name, description, nextId, parameters, key,
						exceptionId, x, y);

				baseComponentNodeInfos.add(baseComponentNodeInfo);
			} catch (Exception e) {
				//如果解析xml出现异常，对整个xml文件的解析将没有意思，所以不在继续解析
				throw new SaturnComponentException("load base component node failed! the key is [" + key
						+ "]", e);
			}
		}
		
		return baseComponentNodeInfos;
	}
}
